#include "NetworkModule.h"
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <algorithm>

NetworkModule::NetworkModule(int port)
    : port(port), serverSocket(-1), running(false)
{
}

NetworkModule::~NetworkModule()
{
    stop();
}

bool NetworkModule::start()
{
    // 创建socket
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1)
    {
        cerr << "Failed to create socket" << endl;
        return false;
    }

    // 设置socket选项
    int opt = 1;
    if (setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1)
    {
        cerr << "Failed to set socket options" << endl;
        close(serverSocket);
        return false;
    }

    // 绑定socket
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
    {
        cerr << "Failed to bind socket" << endl;
        close(serverSocket);
        return false;
    }

    // 监听连接
    if (listen(serverSocket, 5) == -1)
    {
        cerr << "Failed to listen on socket" << endl;
        close(serverSocket);
        return false;
    }

    cout << "Server started on port " << port << endl;
    running = true;

    // 启动接受连接的线程
    acceptThread = thread(&NetworkModule::acceptConnections, this);
    return true;
}

void NetworkModule::stop()
{
    running = false;
    if (serverSocket != -1)
    {
        close(serverSocket);
    }
    if (acceptThread.joinable())
    {
        acceptThread.join();
    }
    // 关闭所有客户端连接
    lock_guard<mutex> lock(clientMutex);
    for (int clientSocket : clientSockets)
    {
        close(clientSocket);
    }
    clientSockets.clear();
}

void NetworkModule::sendMessage(int clientSocket, const string &message)
{
    if (send(clientSocket, message.c_str(), message.length(), 0) == -1)
    {
        cerr << "Failed to send message to client" << endl;
    }
}

void NetworkModule::setMessageCallback(function<void(int, const string &)> callback)
{
    messageCallback = callback;
}

void NetworkModule::setDisconnectCallback(function<void(int)> callback)
{
    disconnectCallback = callback;
}

void NetworkModule::acceptConnections()
{
    while (running)
    {
        sockaddr_in clientAddr;
        socklen_t clientAddrLen = sizeof(clientAddr);
        int clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrLen);

        if (clientSocket == -1)
        {
            if (running)
            {
                cerr << "Failed to accept client connection" << endl;
            }
            continue;
        }

        lock_guard<mutex> lock(clientMutex);
        clientSockets.push_back(clientSocket);

        // 为每个客户端启动一个线程
        thread([this, clientSocket]()
               { handleClient(clientSocket); })
            .detach();
    }
}

void NetworkModule::handleClient(int clientSocket)
{
    char buffer[1024];
    while (running)
    {
        memset(buffer, 0, sizeof(buffer));
        int bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);

        if (bytesRead <= 0)
        {
            // 客户端断开连接
            if (disconnectCallback)
            {
                disconnectCallback(clientSocket);
            }
            close(clientSocket);

            lock_guard<mutex> lock(clientMutex);
            auto it = find(clientSockets.begin(), clientSockets.end(), clientSocket);
            if (it != clientSockets.end())
            {
                clientSockets.erase(it);
            }
            break;
        }

        string message(buffer, bytesRead);
        // 消息如何处理放在上层，回调到上层然后上层再处理调用下来
        if (messageCallback)
        {
            messageCallback(clientSocket, message);
        }
    }
}